import { Form, Input, Button } from 'antd'
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router';
import { getCaptchaAPI, loginAPI } from '@/apis/auth';
import { message } from 'antd';
import { useDebounceFn } from 'ahooks'
import './index.sass'
const Login = () => {

const [messageApi, contextHolder] = message.useMessage();
const navigate = useNavigate();
const [imageCode,SetImageCode] = useState('');
const [formData,SetFormData] = useState({
    username: '',
    pwd: '',
    verifyCode: '',
    verifyCodeId: ''
});
const getCode = () => {
    getCaptchaAPI().then((res:any) => {
        SetImageCode(res.data.imageCode)
        SetFormData({...formData, verifyCodeId:res.data.id })
    })
};

useEffect(() => {
    getCode()
}, [])
 
const { run: onFinish } = useDebounceFn(async (event:any) => {
    let res = await loginAPI({...event,verifyCodeId:formData.verifyCodeId})
    if(res.code === 10000){
        messageApi.success('登陆成功')
        // setToken(res.data?.token as string);
        sessionStorage.setItem('token', res.data!.token);
        navigate('/home')
    }
},{ wait: 500 })

return (<>
    <div className='login_wrapper'>
        { contextHolder }
        <Form 
            onFinish={onFinish}
            onFinishFailed={() => {
                messageApi.error('请先输入正确的数据')
            }}
            size={'large'}
            validateTrigger={['onChange','onBlur']}
        >
            <Form.Item 
                name='username'
                rules={[{required:true,message:'请输入用户名'}]}
            >
                <Input placeholder='用户名' />
            </Form.Item>
            <Form.Item 
                name='pwd'
                rules={[{required:true,message:'请输入密码'}]}
            >
                <Input.Password placeholder='密码' />
            </Form.Item>
            <Form.Item 
                name='verifyCode'
                rules={[
                    { required:true, message:'请输入验证码' },
                    {
                        validator: (_, value) => {
                            if(!value) return Promise.resolve();
                            // 如果输入长度小于5
                            if (value.length < 5) {
                                // 只判断是否包含非数字字母
                                if (/[^0-9A-Za-z]/.test(value)) {
                                return Promise.reject(new Error('验证码只能包含数字或字母'));
                                } else {
                                return Promise.resolve();
                                }
                            // 符合条件
                            } else if (/^[0-9A-Za-z]{5}$/.test(value)) {
                                return Promise.resolve();
                            } else {
                                return Promise.reject(new Error('验证码必须是5位数字或字母'));
                            }
                        }
                        , validateTrigger: 'onchange'
                    },
                    { pattern:/^[a-zA-Z0-9]{5}$/, message:'验证码必须是5位数字或字母', validateTrigger: 'onBlur' }
                ]}
            >
                <div style={{display:'flex',alignItems:'center'}}>
                    <Input placeholder='验证码' maxLength={5} />
                    <img onClick={getCode} src={imageCode} style={{width:'100px',height:'40px',cursor:'pointer'}} />
                </div>
            </Form.Item>
            <Form.Item style={{display:'flex',justifyContent:'center'}}>
                <Button type='primary' htmlType='submit'>
                    提交
                </Button>
            </Form.Item>
        </Form>
    </div>
</>);
}

export default Login;